package com.jine.boot2.controller;

import com.jine.boot2.model.User;
import com.jine.boot2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 新增用户
     * @param name
     * @param pass
     * @return
     */
    @PostMapping("/save")
    public Map<String,Object> saveUser(@RequestParam("name") String name, @RequestParam("pass") String pass){
        Map<String,Object> map = new HashMap<String,Object>();
        User user = new User(name,pass);
        User tempUser = this.userService.saveUser(user);
        map.put("user",tempUser);
        return map;
    }

    /**
     * 获取所有用户
     * @return
     */
    @GetMapping("/list")
    public Map<String, List<User>> listUser(){
        Map<String,List<User>> map = new HashMap<String,List<User>>();
        List<User> list =this.userService.listUser();
        map.put("userList",list);
        return map;
    }

    /**
     * 查询一个用户
     * @param id
     * @return
     */
    @GetMapping("find")
    public Map<String,Object> findUser(@RequestParam("id") String id){
        Map<String,Object> map = new HashMap<String,Object>();
        User user  = this.userService.findUser(id);
        map.put("user",user);
        return map;
    }

    /**
     * 更新用户姓名
     * @param id
     * @param name
     * @return
     */
    @PostMapping("update")
    public Map<String,Object> updateUser(@RequestParam("id") String id,@RequestParam("name") String name){
        Map<String,Object> map = new HashMap<String,Object>();
        User user = this.userService.findUser(id);
        user.setUsername(name);
        this.userService.updateUser(user);
        map.put("result","RC100");
        return map;
    }
    /**
     * 删除一个用户
     * @param id
     * @return
     */
    @GetMapping("delete")
    public Map<String,Object> deleteUser(@RequestParam("id") String id){
        Map<String,Object> map = new HashMap<String,Object>();
        this.userService.deleteUser(id);
        map.put("result","RC100");
        return map;
    }

}
